<template>
    <div class="container">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="算法类别" name="first">
      <el-input v-model="input" style="width: 240px" placeholder="输入算法类别" />
        <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUser">查询</el-button>
        <el-button style="width: 6rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="newUser"  v-if="hasPermission(authStore.permissions,27)">新建算法类别</el-button>
        <!-- 点击新建角色打开 -->
        <el-dialog v-model="visible" :show-close="false" width="800">
      <template #header="{ close }">
        <div class="my-header">
          <div>新建/修改算法类别</div>
          <el-button type="danger" @click="close">
            <el-icon><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>

      <el-tabs v-model="activeNameOne" class="demo-tabs">
        <el-tab-pane label="Step1: 算法类别配置" name="first">
          <div style="display: flex; margin-top: 1rem">
            <div class="input-text">
              <span style="color: red">*</span>算法类别:
            </div>
            <el-input
              style="width: 240px"
              v-model="algorithmTypeName"
              @input="errors.algorithmTypeName = ''"
            ></el-input>
          </div>
          <p v-if="errors.algorithmTypeName" class="error-text">{{ errors.algorithmTypeName }}</p>

          <div style="display: flex; margin-top: 1rem">
            <div class="input-text">
              <span style="color: red">*</span>分析数据源:
            </div>
            <el-select
              v-model="value"
              placeholder="请选择分析数据源"
              style="width: 240px"
              @change="errors.dataType = ''"
            >
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <p v-if="errors.dataType" class="error-text">{{ errors.dataType }}</p>

          <div style="display: flex; margin-top: 1rem">
            <div class="input-text">
              <span style="color: red">*</span>api地址:
            </div>
            <el-input
              style="width: 240px"
              v-model="stepOneApi"
              @input="errors.apiAddress = ''"
            ></el-input>
          </div>
          <p v-if="errors.apiAddress" class="error-text">{{ errors.apiAddress }}</p>

          <div style="margin-top: 1rem">
            <el-upload
              class="upload-demo"
              drag
              :file-list="fileList"
              :limit="1"
              :auto-upload="false"
              accept=".json"
              :on-change="handleFileChange"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽上传或 <em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">请上传 .json 文件</div>
              </template>
            </el-upload>
          </div>

          <p v-if="errors.jsonData" class="error-text">{{ errors.jsonData }}</p>

          <div style="margin-top: 2rem; height: 3rem">
            <div style="width: 100%; display: flex; justify-content: center">
              <el-button style="width: 30%; margin-right: 2rem" @click="visible = false">取消</el-button>
              <el-button style="width: 30%" type="primary" @click="next">下一步</el-button>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="Step2: 子算法解析" name="second">
          <el-table :data="JsonData" style="width: 100%; margin-top: 3rem">
            <el-table-column label="序号" width="100">
              <template #default="{ $index }">
                <span>{{ $index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column label="算法类别" width="150">
              <template #default>
                <span style="color: black">{{ algorithmTypeName }}</span>
              </template>
            </el-table-column>

            <el-table-column label="算法名称" width="250">
              <template #default="{ row }">
                <el-input
                  style="width: 200px"
                  v-model="row.algorithmName"
                  @input="row._error_algorithmName = ''"
                ></el-input>
                <p v-if="row._error_algorithmName" class="error-text">{{ row._error_algorithmName }}</p>
              </template>
            </el-table-column>

            <el-table-column label="缺陷等级" width="300">
              <template #default="{ row }">
                <el-select
                  v-model="row.defectLevel"
                  placeholder="缺陷等级"
                  style="width: 240px"
                  @change="row._error_defectLevel = ''"
                >
                  <el-option
                    v-for="item in optionOne"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <p v-if="row._error_defectLevel" class="error-text">{{ row._error_defectLevel }}</p>
              </template>
            </el-table-column>
          </el-table>

          <div style="margin-top: 2rem; height: 3rem">
            <div style="width: 100%; display: flex; justify-content: center">
              <el-button style="width: 30%" type="primary" @click="before">上一步</el-button>
              <el-button style="width: 30%" type="primary" @click="enter">确认</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>


    <el-table :data="displayedData" style="width: 80%; margin-top: 3rem;">
  <el-table-column label="序号" width="100">
    <template #default="{ row, $index }">
      <span v-if="row.id">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
      <span v-else  style="color:black;opacity: 0;">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>

    </template>
  </el-table-column>

  <el-table-column prop="role.typeName" label="算法类别" width="150">
    <template #default="{ row }">
      <span v-if="row.id"  style="color: black;">{{ row.typeName }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.dataType" label="分析数据源" width="150">
    <template #default="{ row }">
      <span v-if="row.id"  style="color: black;">{{ row.dataType == 'image' ? "图片":"视频" }}</span>

    </template>
  </el-table-column>

  <el-table-column prop="role.apiAddress" label="api地址" width="200">
    <template #default="{ row }">
      <span v-if="row.id"  style="color: black;">{{ row.apiAddress }}</span>

    </template>
  </el-table-column>
  
  <el-table-column fixed="right" label="操作" min-width="200">
    <template #default="{ row }">
      <div v-if="row.id">
        <el-button link type="primary" size="small" @click="changeAlgorithm(row)"  v-if="hasPermission(authStore.permissions,28)" style="color: rgb(110, 78, 208);">编辑</el-button>
        <el-button link type="primary" size="small" @click="deleteTower(row)"  v-if="hasPermission(authStore.permissions,29)" style="color:#f56c6c;">删除</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

<el-dialog v-model="deleteVisible" title="提示" width="500" center>
            <span>
              是否删除算法类别 "{{deleteItem?.typeName}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible = false">取消</el-button>
              <el-button type="primary" @click="deleteAlgorithm()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>
  </el-tab-pane>
  <el-tab-pane label="算法列表" name="second">
    <el-input v-model="inputTwo" style="width: 240px" placeholder="输入算法类别" />
    <el-input v-model="inputThree" style="width: 240px;margin-left: 2rem;" placeholder="输入算法名称" />
        <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUserTwo">查询</el-button>
    <el-table :data="displayedData1" style="width: 80%; margin-top: 3rem;">
  <el-table-column label="序号" width="100">
    <template #default="{ row, $index }">
      <span v-if="row.typeName">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
      <span v-else style="color: transparent;">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
    </template>
  </el-table-column>

  <el-table-column prop="role.algorithm.algorithmName" label="算法名称" width="150">
    <template #default="{ row }">
      <span  style="color: black;">{{ row?.algorithm?.algorithmName }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.algorithm.dataType" label="分析数据源" width="150">
    <template #default="{ row }">
      <span v-if="row.algorithm"  style="color: black;">{{ row?.algorithm?.dataType == 'image'? '图片':'视频' }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="算法类别" width="200">
    <template #default="{ row }">
      <span  style="color: black;">{{ row?.typeName }}</span>

    </template>
  </el-table-column>

  <el-table-column prop="role.algorithm.apiAddress" label="api地址" width="200">
    <template #default="{ row }">
      <span  style="color: black;">{{ row?.algorithm?.apiAddress }}</span>

    </template>
  </el-table-column>
  
  <el-table-column prop="role.algorithm.defectLevel" label="缺陷等级" width="200">
    <template #default="{ row }">
      <span  style="color: rgb(110, 78, 208);">{{ row?.algorithm?.defectLevel }}</span>

    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total1"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

  </el-tab-pane>
      </el-tabs>
    </div>
</template>

<script lang="ts" setup>
    import { hasPermission } from '@/utils/permissionUtils';
    import { CircleCloseFilled , UploadFilled } from '@element-plus/icons-vue';
    import { ref ,onMounted ,nextTick ,onUnmounted} from 'vue'
    import request from '@/utils/request';
    import { useAuthStore } from '@/stores/user';
    import {type UploadFile} from 'element-plus';
    import { ElMessage } from 'element-plus';
    import type { TabsPaneContext } from 'element-plus'
    import showMessage from '@/utils/showMessage';
      const errors = ref({
      algorithmTypeName: '',
      dataType: '',
      apiAddress: '',
      jsonData: ''
    });

    const authStore = useAuthStore();//使用store仓库进行数据管理
    const activeName = ref('first')
    const activeNameOne = ref('first')
    const value = ref('')   
    const tableData = ref([]); // 原始数据
    const tableData1 = ref([]); // 原始数据

    const displayedData = ref([]); // 当前页显示的数据
    const displayedData1 = ref([]); // 当前页显示的数据

    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页条数
    const total = ref(0); // 总条数
    const total1 = ref(0); // 总条数

    const input = ref('')
    const inputTwo = ref('')
    const inputThree = ref('')
    const visible = ref(false)
    const algorithmTypeName = ref()
    const stepOneApi = ref()
    const flag = ref()
    const changeItemId = ref()
    // 新建角色
    const newUser= () => {
      errors.value = {
      algorithmTypeName: '',
      dataType: '',
      apiAddress: '',
      jsonData: ''
    }
      flag.value = 1
      visible.value = true;
      algorithmTypeName.value = ''
      value.value = ''
      stepOneApi.value = ''
      fileList.value =  []
      JsonData.value = []
      activeNameOne.value = 'first'
    }

    const options = [
  {
    value: 'image',
    label: '图片',
  },
  {
    value: 'video',
    label: '视频',
  },
]

const optionOne = [
  {
    value: '一般',
    label: '一般',
  },
  {
    value: '危机',
    label: '危机',
  },
  {
    value: '严重',
    label: '严重',
  },
  {
    value: '不告警',
    label: '不告警',
  },
]
const validateStepOne = () => {
  let isValid = true;
  if (!algorithmTypeName.value) {
    errors.value.algorithmTypeName = '请输入算法类别';
    isValid = false;
  }
  if (!value.value) {
    errors.value.dataType = '请选择分析数据源';
    isValid = false;
  }
  if (!stepOneApi.value) {
    errors.value.apiAddress = '请输入 api 地址';
    isValid = false;
  }
  if (!JsonData.value.length) {
    errors.value.jsonData = '请上传 .json 文件';
    isValid = false;
  }
  return isValid;
};

const validateJsonTable = () => {
  let isValid = true;
  JsonData.value.forEach((item: any) => {
    if (!item.algorithmName) {
      item._error_algorithmName = '请输入算法名称';
      isValid = false;
    }
    if (!item.defectLevel) {
      item._error_defectLevel = '请选择缺陷等级';
      isValid = false;
    }
  });
  return isValid;
};

  // 下一步，上一步方法
    const  next = () => {
      if (!validateStepOne()) return;
        activeNameOne.value = 'second'
    }
    const  before = () => {
        activeNameOne.value = 'first'
    }
    const enter = () => {
      if (!validateJsonTable()) return;
      if(flag.value == 1){


      if( !algorithmTypeName.value || !value.value || !stepOneApi.value || !JsonData.value){
        ElMessage({
             message: '表单未完成填写',
             type: 'warning',
          });

        return
      }
      const formData = new FormData()
      const algorithmType = {
        typeName:algorithmTypeName.value,
        dataType:value.value,
        apiAddress:stepOneApi.value
      }
      formData.append("algorithmType",JSON.stringify(algorithmType))
      formData.append("algorithms",JSON.stringify(JsonData.value))

      request.post("/resource/insertAlgorithm",formData).then((res)=> {
        if(res.data.status == 'success'){
          getAllAlgorithmType()//获取全部算法
          ElMessage({
             message: '新建成功',
             type: 'success',
          });

          request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"新增算法列表成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              })

              getAllAlgorithmType()//获取全部算法

              visible.value = false

        }
      })
    }else if(flag.value == 2) {

      const formData = new FormData()
      const algorithmType = {
        typeName:algorithmTypeName.value,
        dataType:value.value,
        apiAddress:stepOneApi.value,
        id:changeItemId.value
      }
      formData.append("algorithmType",JSON.stringify(algorithmType))
      formData.append("algorithms",JSON.stringify(JsonData.value))
      request.post("/resource/updateAlgorithm",formData).then((res)=> {
        if(res.data.status == 'success'){

          ElMessage({
             message: '修改成功',
             type: 'success',
          });

          request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"修改算法成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              })

              getAllAlgorithmType()//获取全部算法

              visible.value = false

        }
      })


    }
  }

    // json文件上传相关

    const fileList = ref<UploadFile[]>([]);

    const JsonData = ref([])//用于存储解析后的json数据
    
    // 处理文件变化
    const handleFileChange = (file: UploadFile, files: UploadFile[]) => {
      fileList.value = files;

    
  // 获取上传的第一个文件
  const uploadedFile = file.raw;

// 只处理 JSON 文件
if (uploadedFile && uploadedFile.type === 'application/json') {
  const reader = new FileReader();

  // 文件读取完成后执行
  reader.onload = () => {
    if (typeof reader.result === 'string') {
      try {
        // 解析 JSON 数据
        const jsonData = JSON.parse(reader.result);

        JsonData.value = jsonData

      } catch (error) {
        console.error('JSON 解析失败:', error);
      }
    } else {
      console.error('文件内容不是有效的文本');
    }
  };

  // 读取文件内容
  reader.readAsText(uploadedFile);
} else {
  console.error('请选择一个有效的 JSON 文件');
}
    };


    // 获取全部算法类别

    const getAllAlgorithmType = () => {
      request.get("resource/getAllAlgorithmType").then((res:any) => {
        tableData.value = res.data
        total.value = res.data.length;
        updateDisplayedData();
      })
    }

    // 获取全部算法列表
    const getAllAlgorithm = () => {
      request.get("resource/getAllAlgorithm").then((res:any) =>{
   
        tableData1.value = res.data
        total1.value = res.data.length;
        updateDisplayedData1();
      })
    }

    //编辑按钮
   const  changeAlgorithm = (row:any) => {
    errors.value = {
      algorithmTypeName: '',
      dataType: '',
      apiAddress: '',
      jsonData: ''
    }
      changeItemId.value = row.id
      flag.value = 2
      visible.value = true 
      request.post("resource/getAlgorithmByAlgorithmTypeID" ,{
        id:row.id
      }).then((res:any)=> {
        algorithmTypeName.value = row.typeName
        value.value = row.dataType
        stepOneApi.value = row.apiAddress
        JsonData.value = res.data
      })

   } 


   const handleClick = (tab: TabsPaneContext, event: Event) => {
      currentPage.value = 1
      getAllAlgorithmType()
      getAllAlgorithm()
      }
  
    // 筛选数据
    const filterUser = () => {
          const formData = new FormData()
          formData.append('typeName',input.value || '')
          request.post("/resource/getAlgorithmTypeByCondition" ,formData).then(
            (res)=>{
              if(res.status == 200){
                tableData.value = res.data
                total.value = res.data.length;
                updateDisplayedData();
            }
            }
          )
    }
    const filterUserTwo = () => {
          const formData = new FormData()
          formData.append('typeName',inputTwo.value || '')
          formData.append(' algorithmName',inputThree.value || '')

          request.post("/resource/getAlgorithmByCondition" ,formData).then(
            (res)=>{
              if(res.status == 200){
                tableData1.value = res.data
                total1.value = res.data.length;
                updateDisplayedData1();
            }
            }
          )
    }
    // 删除逻辑

    const deleteVisible = ref(false)
    const deleteItem = ref()
    const deleteTower = (row:any) => {
      deleteVisible.value = true
      deleteItem.value = row
    }
    const deleteAlgorithm =() => {
        request.post("/resource/deleteAlgorithmTypeByID",{id:deleteItem.value.id}).then(
          (res)=>{
            showMessage(res)
            if(res.data.status == 'success'){
             deleteVisible.value = false
            //删除用户日志 
              request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"删除算法类别",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              })
              // 获取所有用户信息
              getAllAlgorithmType()
            }
          }
        )
    }


  
// 更新显示的数据
const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};
const updateDisplayedData1 = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData1.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData1.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};


  const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 10 : 20; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    getAllAlgorithmType()
    getAllAlgorithm()
  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});

</script>

<style scoped>
.container {
    width: 100%;
    height: calc(100vh - 100px);
    display: block;
    padding: 20px;
    box-sizing: border-box;
}
.container-head {
    display: flex
} 
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.input-text {
    width: 20%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.input-text1 {
    width: 10%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.selected-tab {
  background-color: #409eff;
  color: white;
}
.empty-row {
  background-color: #f5f7fa;
  color: gray;
  text-align: center;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.error-text {
  color: red;
  font-size: 12px;
  margin-left: 5rem;
  margin-top: 0.25rem;
}
</style>